<template>
  <div>
    <!-- <aside-tree
      title="安检任务单"
      :tree-data="treeData"
      :mouse-button="false"
      :loading="$loadingPlugin.getTreeData"
      @currentChange="currentChange"
      @refresh="getTreeData"
    /> -->
    <div class="table">
      <el-table-form ref="form">
        <el-form-item label="" prop="" :table-form-merge="1">
          <el-select v-model="choose" placeholder="" style="width: 40%;">
            <el-option
              v-for="item in chooseMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
          <el-input
            v-model="inpuntText"
            style="width: 58%;"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item :table-form-merge="2" class="merge-item">
          <el-select v-model="timeType" style="width: 170px; margin-right: 2px;">
            <el-option label="派单时间" value="createTime" />
            <el-option label="处理时间" value="modifyTime" />
          </el-select>
          <el-date-picker
            v-model="date"
            type="datetimerange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item label="所属机构:" prop="orgSNNo">
          <el-tree-select
            v-model="query.orgSNNo"
            :clearable="false"
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData,
            }"
            :tree-params="{
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props: {
                value: 'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData,
            }"
            @node-click="selectTreeChange"
          />
        </el-form-item>
        <el-form-item :table-form-merge="0.2">
          <el-checkbox v-model="query.option" label="包含下级" />
        </el-form-item>
        <el-form-item class="merge-item" label="客户类型:">
          <el-select v-model="query.csmType" placeholder="请选择" clearable>
            <el-option v-for="(i, ind) in clientList" :key="ind" :label="i.desc" :value="i.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item class="merge-item" :table-form-merge="1.1">
          <el-select v-model="conditionType" style="width: 180px; margin-right: 2px;">
            <el-option label="客户电话" value="csmPhone" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <el-option label="客户地址" value="csmAddress" />
            <el-option label="派单人" value="createUser" />
            <el-option label="处理人" value="checkUser" />
            <el-option label="关联安检单号" value="checkId" />
          </el-select>
          <el-input v-model.trim="conditionText" placeholder="请输入" clearable />
        </el-form-item> -->
        <el-form-item class="merge-item" label="状态:">
          <el-select v-model="query.planDetailStatus" placeholder="请选择" clearable>
            <el-option v-for="(i, ind) in enumerationType" :key="ind" :label="i.desc" :value="i.value" />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button v-permission="[60102, 1]" type="primary" icon="el-icon-search" :loading="$loadingPlugin.fetchData" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;" class="btn-group">
        <div>
          <el-button v-permission="[60102, 2]" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          <el-button v-permission="[60102, 3]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :immediate-fetch="false"
        default-open
        @fetch="fetchData"
      />
    </div>
    <add ref="add" @upDataTable="upDataTable" />
    <check-roam-info ref="roamInfo" />
    <check-transfer ref="transferOrder" />
    <security-check-detail ref="securityCheckDetail" :warn-level-map="warnLevelMap" :index-table-data="[]" :tree-data="treeData" />
    <csm-detail ref="csmDetail" :parent-fetch-data="refresh" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
    <OrderDetail ref="orderDetail" />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { queryMap, queryCsmTypeMap, gasCheckTodoList, gasCheckTodoExport, queryExportDomain, gasCheckTodoCancellation, queryRiskTrackMap } from '@/api'
  import moment from 'dayjs'
  import Add from './components/Add.vue'
  import CheckRoamInfo from './components/CheckRoamInfo'
  import CheckTransfer from './components/CheckTransfer'
  import SecurityCheckDetail from '../securityOrderManage/components/securityOrderInfo.vue'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import { mapGetters } from 'vuex'

  export default {
    name: 'addition',
    components: {
      CheckRoamInfo,
      CheckTransfer,
      Add,
      SecurityCheckDetail,
      CsmDetail,
      OrderDetail: () => import('../../orderCenter/orderManage/components/OrderDetails.vue')
    },
    data() {
      return {
        treeData: [],
        clientList: [],
        enumerationType: [],
        actionColWidth: 80,
        exportDomain: {},
        warnLevelMap: [],
        calcTypeList: [],
        paymenFilList: [],
        choose: 'csmPhone',
        inpuntText: '',
        chooseMap: [
          { desc: '客户电话', value: 'csmPhone' },
          { desc: '客户编号', value: 'csmCode' },
          { desc: '客户名称', value: 'csmName' },
          { desc: '客户地址', value: 'csmAddress' },
          { desc: '派单人', value: 'createUser' },
          { desc: '处理人', value: 'checkUser' },
          { desc: '任务单号', value: 'planCode' },
          { desc: '关联安检单号', value: 'checkId' },
          { desc: '安检机构', value: 'orgName' }
        ],
        query: {
          orgSNNo: '',
          csmType: '',
          planDetailStatus: '',
          pageIndex: '',
          pageSize: '',
          option: false
        },
        checkTypeMap: [
          { value: 1, desc: '随单安检', key: 'SD' },
          { value: 2, desc: '定期安检', key: 'JH' }
        ],
        conditionText: '',
        conditionType: 'csmPhone',
        timeType: 'createTime',
        date: [moment().startOf('month'), moment().endOf('day')],
        searchParams: {},
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            // width: 100,
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          },
          {
            prop: 'csmName',
            label: '客户名称'
            // width: 100
          },
          {
            prop: 'contact',
            label: '联系人',
            width: 110
          },
          {
            prop: 'csmPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'csmType',
            label: '客户类型',
            // width: 100,
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.clientList, 'value', row.csmType, 'desc') }</span>
          },
          {
            prop: 'csmAddress',
            label: '联系地址',
            width: 260,
            render: (h, { row }) => {
              const s = row.provinceName && row.provinceName
              const v = row.cityName && row.cityName
              const x = row.countryName && row.countryName
              const z = row.csmAddress && row.csmAddress
              const q = row.streetName && row.streetName
              return <span>{s}{v}{x}{q}{z}</span>
            }
          },
          {
            prop: 'nearStationName',
            label: '所属机构',
            width: 120
          },
          {
            prop: 'orgName',
            label: '安检机构',
            width: 120
          },
          {
            prop: 'planDetailStatus',
            label: '状态',
            // width: 100,
            render: (h, { row }) => <span>{ row.planDetailStatus && formatColumnMap(this.enumerationType, 'value', row.planDetailStatus, 'desc') }</span>
          },
          {
            prop: 'checkId',
            label: '关联安检单',
            width: 100,
            render: (h, { row }) => {
              if (row.checkId === 0) {
                return ''
              }
              return <el-link underline={false} onClick={() => this.openSecurityCheckDetail(row)}>{row.checkId}</el-link>
            }
          },
          {
            prop: 'checkUser',
            label: '处理人'
            // width: 100
          },
          {
            prop: 'driverName',
            label: '大车司机',
            showOverflowTooltip: true
          },
          {
            prop: 'escortName',
            label: '押运员',
            showOverflowTooltip: true
          },
          {
            prop: 'modifyTime',
            label: '处理时间',
            width: 160,
            render: (h, { row }) => <span>{ row.planDetailStatus === 2 && row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      {row.planDetailStatus === 1 && (<el-dropdown-item>
                        <el-link v-permission={[60102, 4]} underline={false} size='mini' onClick={() => this.openTransferOrder(row)}>转派</el-link>
                      </el-dropdown-item>)}
                      <el-dropdown-item>
                        <el-link v-permission={[60102, 5]} underline={false} size='mini' onClick={() => this.openFlow(row)}>流转信息</el-link>
                      </el-dropdown-item>
                      {row.planDetailStatus === 1 && (<el-dropdown-item>
                        <el-link v-permission={[60102, 6]} underline={false} type='danger' size='mini' onClick={() => this.cancellation(row)}>作废</el-link>
                      </el-dropdown-item>)}
                     </el-dropdown-menu>
                  </el-dropdown>
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTreeData()
      await this.getUserType()
      await this.queryOptionsMap()
      await this.getExportDomain()
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        this.query.pageIndex = currentPage
        this.query.pageSize = pageSize
        const params = {
          ...this._getQuery(this.query)
        }
        this.conditionText ? params[this.conditionType] = this.conditionText : ''
        if (this.date && this.date.length === 2) {
          params[this.timeType] = this.date[0]
          params[`${this.timeType}End`] = this.date[1]
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        const res = await gasCheckTodoList(params)
        this.searchParams = params
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询
      async search() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async refresh() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 更新数据
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 新增
      async add(row) {
        await this.$refs.add.open(row)
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          gasCheckTodoExport({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 打开关联订单
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 点击流转信息
      async openFlow(row) {
        await this.$refs.roamInfo.open(row)
      },
      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch()
      },
      // 作废
      cancellation(val) {
        const me = this
        // console.log('val', val)
        this.$confirm('作废安检任务单，确定要执行吗？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await gasCheckTodoCancellation({ planCode: val.planCode, csmAddressId: val.csmAddressId })
          console.log('res', res)
          if (res.status === 200) {
            me.$message({
              type: 'success',
              message: '作废安检任务成功!'
            })
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消'
          // })
        })
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        if (this.choose === 'csmPhone') {
          query.csmPhone = this.inpuntText
        }
        if (this.choose === 'csmCode') {
          query.csmCode = this.inpuntText
        }
        if (this.choose === 'csmName') {
          query.csmName = this.inpuntText
        }
        if (this.choose === 'csmAddress') {
          query.csmAddress = this.inpuntText
        }
        if (this.choose === 'createUser') {
          query.createUser = this.inpuntText
        }
        if (this.choose === 'checkUser') {
          query.checkUser = this.inpuntText
        }
        if (this.choose === 'planCode') {
          query.planCode = this.inpuntText
        }
        if (this.choose === 'checkId') {
          query.checkId = this.inpuntText
        }
        if (this.choose === 'orgName') {
          query.orgName = this.inpuntText
        }
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        query.orgId = this.query.option ? 0 : this.query.orgId
        return query
      },
      // 选择组织机构变化
      currentChange(current) {
        if (current.orgSNNo) {
          this.query.orgSNNo = current.orgSNNo
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          this.$message({
            message: '请选择机构',
            type: 'warning'
          })
        }
      },
      // 获取组织机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.query.orgSNNo = this.orgList && this.orgList[0].orgSNNo
        this.query.orgId = this.orgList && this.orgList[0].orgId
        this.selectTreeChange(this.orgList[0])
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.query.orgSNNo = value.orgSNNo
        this.query.orgId = value.orgId
        this.$nextTick(() => {
          this.$refs.lbTable.fetch({ currentPage: 1 })
        })
      },
      // 客户类型
      async getUserType() {
        try {
          const res = await queryCsmTypeMap()
          this.clientList = res.data
        } catch (error) {
          console.log(error)
        }
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([mergeAsyncFunc(queryMap, { enumName: 'PlanDetailStatus' }), mergeAsyncFunc(queryMap, { enumName: 'CalcType' }), mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' })])
        this.enumerationType = res1.data
        this.calcTypeList = res2.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res3.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        const res4 = await queryRiskTrackMap()
        this.warnLevelMap = JSON.parse(res4.data.warnLevel) // 隐患等级
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 关联安检单
      async openSecurityCheckDetail(row) {
        await this.$refs.securityCheckDetail.open(row, '任务单详情')
      },
      // 打开客户详情弹窗
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      }
    }
  }
</script>

<style lang="scss" scoped>
  .table {
    width: 100%;
    margin: 0 10px;
  }
</style>
